//
//  YoucApiTask.m
//  YoucApi
//
//  Created by Liam on 12-11-3.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "YoucApiTask.h"
#import "CmnFunc.h"
#import "JSONKit.h"

@implementation YoucApiTask

- (NSError *)_checkEnvBeforeProcess
{
	NSError * error = nil;
	
	if (![CmnFunc checkCanUseNetwork])
	{
		error = [YoucApiError errorWithCode:YoucApiErrorNoConnection userInfo:nil];
	}

	return error;
}

- (NSString *)_getMethod
{
	return @"POST";
}

- (NSString *)_getRequestParams
{
	return nil;
}

- (NSString *)_getRequestURI
{
	NSDictionary *jsonDict = [NSDictionary dictionaryWithObjectsAndKeys:
							  [self _getKeys], KEY_KEYS,
							  [self _getMessage], KEY_MESSAGE,
							  [self _getRequest], KEY_REQUEST, nil];
	
	NSError *error = nil;
	NSString * json = [jsonDict JSONStringWithOptions:JKSerializeOptionNone error:&error];
	
	NSString * uri = [NSString stringWithFormat:@"/index.php?c=%@&a=%@&json=%@",
					  SAFE_FORMAT_STRING([self _getUriParamC]),
					  SAFE_FORMAT_STRING([self _getUriParamA]),
					  [CmnFunc URLEncode:json], nil];
	
	return uri;
}

//- (NSDictionary *)_getHeaders
//{
//	NSMutableDictionary * headers = [NSMutableDictionary dictionary];
//	
//	[headers setValue:@"application/json; charset=utf-8" forKey:@"Content-Type"];	
//	
//	NSDictionary* superHeaders = [super _getHeaders];
//	if (superHeaders)
//	{
//		[headers setValuesForKeysWithDictionary:superHeaders];
//	}
//	
//	return headers;
//}

//- (NSData *)_getHTTPBody
//{
//	NSDictionary *dictBody = [NSDictionary dictionaryWithObjectsAndKeys:
//							  [self _getKeys], KEY_KEYS,
//							  [self _getMessage], KEY_MESSAGE,
//							  [self _getRequest], KEY_REQUEST, nil];
//	
//	NSError *error = nil;
//	
//	NSData *data = [dictBody JSONDataWithOptions:JKSerializeOptionNone error:&error];
//	
//	if (error)
//	{
//		NSLog(@"json data error:%@", error);
//	}
//	else
//	{
//		NSLog(@"json data %@", data);
//	}
//	
//	return data;
//}

- (NSString *)_getKeys
{
	return @"4ef2710c9b1b1a4be93a7dd5f5be192b";
}

- (NSString *)_getMessage
{
	return @"";
}

- (id)_getRequest
{
	NSMutableDictionary *dictReqest = [NSMutableDictionary dictionary];
	
	for (NSString* key in [self.params allKeys])
	{
		if ([self _ignoreParamKey:key])
			continue;
		
		[dictReqest setObject:[self.params valueForKey:key] forKey:key];
	}
	
	//return [NSArray arrayWithObject:dictReqest];
	return dictReqest;
}

- (NSString *)_getUriParamC
{
	return nil;
}

- (NSString *)_getUriParamA
{
	return nil;
}

- (BOOL)_checkValidResponse:(id)responseObject;
{
	return YES;
}

- (NSInteger)apiErrorCodeFromErrorCode:(NSInteger)code
{
    return code;
}

- (NSError *)youcApiErrorFromSystemError:(NSError *)error
{
	int code = YoucApiErrorUnkown;
	
	if ([[error domain] isEqualToString:NSURLErrorDomain])
	{
		// change NSURLError to YoucApiError
		code = YoucApiErrorRequestConnect;
		
		if (error)
		{
			switch ([error code]) {
				case NSURLErrorTimedOut:
					code = YoucApiErrorRequestTimeOut;
					break;
				case NSURLErrorCannotParseResponse:
					code = YoucApiErrorInvalidResponse;
					break;
				case NSURLErrorCancelled:
					code = YoucApiErrorUserCancelled;
					break;
				default:
					break;
			}
		}
	}
	
	error = [YoucApiError errorWithCode:code userInfo:nil];
	
	return error;
}

- (id)getResponseFromJSON:(NSDictionary *)jsonDict withError:(NSError**)error
{
	id responseObject = nil;
	
	NSError *errRet = *error;

	NSString *strKeys = [jsonDict objectForKey:KEY_KEYS];
	NSString *strCode = [jsonDict objectForKey:KEY_ERROR_CODE];
	NSString *strMsg = [jsonDict objectForKey:KEY_MESSAGE];
	responseObject = [jsonDict objectForKey:KEY_RESPONSE];

	if (strKeys && strCode && strMsg && responseObject)
	{
        NSInteger errCode = [strCode intValue];
		if (errCode != YoucApiErrorSuccess)
		{
            errCode = [self apiErrorCodeFromErrorCode:errCode];
            
			errRet = [YoucApiError errorWithCode:errCode userInfo:[NSDictionary dictionaryWithObject:strMsg forKey:NSLocalizedDescriptionKey]];
		}
		else if (![self _checkValidResponse:responseObject])
		{
			errRet = [YoucApiError errorWithCode:YoucApiErrorInvalidResponse userInfo:nil];
		}
	}
	else
	{
		errRet = [YoucApiError errorWithCode:YoucApiErrorInvalidResponse userInfo:nil];
	}
	
	if (*error)
		*error = errRet;
	
	return responseObject;
}

- (void)_dealWithResponse:(NSData *)data withError:(NSError *)error
{
	if (error && ![[error domain] isEqualToString:YoucApiErrorDomain])
	{
		error = [self youcApiErrorFromSystemError:error];
	}
	else if (!error)
	{
		error = [YoucApiError errorWithCode:YoucApiErrorSuccess userInfo:nil];
	}

	id responseObject = nil;
	
	if ( [error code] == YoucApiErrorSuccess && data && [data length] )
	{
		// parse json data
		NSError *jsonError = nil;
		NSDictionary *jsonDict = [data objectFromJSONDataWithParseOptions:JKParseOptionLooseUnicode error:&jsonError];
		
		NSLog(@"jsonDict %@ error %@", [jsonDict description], jsonError);
		
		if (jsonDict && [jsonDict isKindOfClass:[NSDictionary class]])
		{
			responseObject = [self getResponseFromJSON:jsonDict withError:&error];
		}
//	#ifdef _DEBUG
//		else
//		{
//			NSString * str = [[[NSString alloc] initWithData:data encoding:[NSString defaultCStringEncoding]] autorelease];
//			NSLog(@"return data %@", str);
//		}
//	#endif
	}
	
	if (!responseObject)
	{
		error = [YoucApiError errorWithCode:YoucApiErrorInvalidResponse userInfo:nil];
	}
	
	switch ([error code]) {
		case YoucApiErrorInvalidSession:
		case YoucApiErrorSessionTimeout:
			[[NSNotificationCenter defaultCenter] postNotificationName:YAInvalidSessionNotification object:self userInfo:nil];
			break;
			
		default:
			break;
	}


	[self _dealWithJSONResponse:responseObject withError:error];
	
	//NSLog(@"_dealWithJSONResponse error %@", [error description]);

}

- (void)_dealWithJSONResponse:(id)responseObject withError:(NSError *)error
{

}

@end
